unit ec_setselfswitch;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons,
  StdCtrls, ec_base, fpjson;

type

  { TECSelfSwitchFrame }

  TECSelfSwitchFrame = class(TECBaseFrame)
    NewValueGroupBox: TGroupBox;
    OffRadioButton: TRadioButton;
    OnRadioButton: TRadioButton;
    SelfSwitchComboBox: TComboBox;
    SelfSwitchToSetGroupBox: TGroupBox;
  private
    HasCustomSelfSwitch: Boolean;
    procedure InitialSetup;
  public
    procedure InitNew; override;
    procedure InitExisting; override;
    procedure MakeResultingCommand; override;

  end;

var
  ECSelfSwitchFrame: TECSelfSwitchFrame;

implementation

{$R *.lfm}

uses
  comboboxhelper, constants;

{ TECSelfSwitchFrame }

procedure TECSelfSwitchFrame.InitialSetup;
begin
  FillUserSelfSwitchNameCombobox(SelfSwitchComboBox);
  HasCustomSelfSwitch := False
end;

procedure TECSelfSwitchFrame.InitNew;
begin
  InitialSetup;
  {TODO}
end;

procedure TECSelfSwitchFrame.InitExisting;
var
  Params: TJSONArray;

  SelfSwitchName: String = 'A';
  SelfSwitchId: Integer = -1;
  IsOff: Boolean;
begin
  InitialSetup;

  Params := GetFirstParams;
  if (Params.Count >= 1) and (Params[0].JSONType = jtString) then
    SelfSwitchName := Params.Strings[0];

  if Length(SelfSwitchName) = 1 then
    case SelfSwitchName[1] of
      'A': SelfSwitchId := 0;
      'B': SelfSwitchId := 1;
      'C': SelfSwitchId := 2;
      'D': SelfSwitchId := 3;
    end;

  if SelfSwitchId = -1 then begin
    SelfSwitchComboBox.Items.Add(SelfSwitchName);
    SelfSwitchId := SelfSwitchComboBox.Items.Count - 1;
    HasCustomSelfSwitch := True
  end;

  SelfSwitchComboBox.ItemIndex := SelfSwitchId;

  if (Params.Count >= 2) and (Params[1].JSONType = jtBoolean) then
    IsOff := Params.Booleans[1];

  if IsOff then
    OffRadioButton.Checked := True
  else
    OnRadioButton.Checked := True
end;

procedure TECSelfSwitchFrame.MakeResultingCommand;
var
  SelfSwitchName: String;
  SelfSwitchAction: Integer;
begin
  if HasCustomSelfSwitch and
        (SelfSwitchComboBox.ItemIndex = SelfSwitchComboBox.Items.Count -1) then
    SelfSwitchName := SelfSwitchComboBox.Items[SelfSwitchComboBox.ItemIndex]
  else
    SelfSwitchName := Chr(Ord('A') + SelfSwitchComboBox.ItemIndex);


  if OffRadioButton.Checked then
    SelfSwitchAction := 1
  else
    SelfSwitchAction := 0;

  ResultingCommand := TJSONArray.Create([
    TJSONObject.Create([
      'code', SET_SELF_SWITCH_EC_CODE,
      'indent', Indent,
      'parameters', TJSONArray.Create([
        SelfSwitchName,
        SelfSwitchAction
      ])
    ])
  ]);
end;

end.

